@extends('layouts/app')

@section('content')
    <div class="order-info takeout">
        <form action="" name="info" id="info">
            @csrf

        </form>
    </div>

    {{--预定面板--}}
    <div class="order-info book" style="display: none;">
        <form action="" name="info" id="info">
            @csrf
            <div class="order-panel">
                <div class="order-header">
                    <h3 class="shop-name arrow-right">
                        <svg class="icon f48" aria-hidden="true">
                            <use xlink:href="#icon-weibiaoti--3"></use>
                        </svg>
                        <span class="f30">我是标题</span>
                        {{--<svg class="icon f20 pull-right" aria-hidden="true">--}}
                        {{--<use xlink:href="#icon-tubiao-2"></use>--}}
                        {{--</svg>--}}
                    </h3>
                </div>
                <div class="order-content">
                    <div class="foods">

                    </div>
                    <div class="foods-info">
                        <p class="f18 gary9">预定时间 <span class="f28 gary9 pull-right time"></span></p>
                        <p class="f18 gary9">优惠金额 <span class="f28 gary9 pull-right">￥ <span class="prePrice"></span></span></p>
                        <p class="f18 gary9">总计 <span class="f28 gary9 pull-right">￥<span class="total"></span></span></p>
                    </div>
                </div>
            </div>
            <div class="order-panel">
                <div class="order-header">
                    <h3 class="f30">备注</h3>
                </div>
                <div class="order-content">
                    <textarea name="content" class="content" rows="5" style="width: 100%;border: 1px dashed #dbdbdb;"></textarea>
                </div>
            </div>
            <div class="order-panel">
                <div class="order-header">
                    <h3 class="f30">个人信息</h3>
                </div>
                <div class="order-content">
                    <div class="weui-cells_form">
                        <div class="weui-cell">
                            <div class="weui-cell__hd"><label class="weui-label f28">姓名</label></div>
                            <div class="weui-cell__bd">
                                <input class="weui-input f28" type="text" name="name" placeholder="请输入姓名">
                            </div>
                        </div>
                        <div class="weui-cell">
                            <div class="weui-cell__hd"><label class="weui-label f28">手机号</label></div>
                            <div class="weui-cell__bd">
                                <input class="weui-input f28" type="number" name="phone" placeholder="请输入手机号">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="weui-cell no-border">
                <button type="button" class="weui-btn weui-btn_primary f30" onclick="doOrder()">提交</button>
            </div>
        </form>
    </div>

    <script>

        window.addEventListener('pageshow', function(e) {
        //如果检测到页面是从“往返缓存”中读取的，刷新页面
            if (e.persisted) {
                window.location.reload();
            }
        });

        // 下单接口
        var api = {
            'takeout': '/api/TaddOrder', // 外卖
            'book'   : '/api/RaddOrder', // 预定
            'sweep'  : '/api/SaddOrder'  // 扫码点餐
        };

        //获取url参数
        var shopsId   = getRequest().shopsId,              //店铺ID
            type      = decodeURI(getRequest().type) || "";//类型
            _token    = $("input[name='_token']").val();    //token
        getUserInfo(_token, function (userInfo){

            //请求后台校验
            $.post('/api/check_shop', {shopsId:shopsId,type:type}, function (res) {
                if (typeof res === 'string') {
                    res = JSON.parse(res);
                }
                console.log(res)
                if(res.code!=200){
                    alert(res.info);
                    history.back();
                }
                var shopsName= res.data.shop_name;
                if (type == 'takeout') {//外卖
                    var shopsSpend = res.data.shopinfo.spend;//配送费
                    var address = getMyAddress(_token); //获取用户选择地址
                    // 如果没有选择地址，给出用户的默认地址
                    if (!address.status) {
                        address = userInfo[0].default_addresses
                    }

                } else if (type == 'book') {//预定
                    // 获取预定时间
                    var arriveTime = Storage.get('arriveTime');
                    if (arriveTime.status){
                        arriveTime = arriveTime.value;              //预定时间
                    }
                    // 获取预定房桌信息
                    var desk_room = Storage.get('deskRoom');
                    if (desk_room.status) {
                        desk_room = JSON.parse(desk_room.value);
                    }
                } else if (type == 'sweep') {//扫码
                    var room_desk_id = getRequest().room_desk_id;
                }else{
                    alert("下单类型不存在");
                    history.back();
                }
                var carData = getShopsCarData(shopsId);
                //预定下单页面
                if(!carData){
                    alert('购物车为空')
                    if(type == 'book'){
                        location.href = '/mobile/shops/' + shopsId;
                    }else{
                        history.back();
                    }
                }

                var data = {};
                data['type'] = 'takeoutOrder';
                data['element'] = '#info';
                data['data'] = carData;          //购物车数据
                data['order_type'] = type;       //下单类型
                data['shops_id'] = shopsName;    // 店铺ID
                data['shops_name'] = shopsName;  // 店铺名称
                data['shops_spend'] = shopsSpend;// 配送费
                data['addressInfo'] = address;
                data['arriveTime'] = arriveTime; // 预定时间
                data['room_desk_id'] = room_desk_id;  //当前房桌（扫码点餐）
                // 房桌（预定）
                if (desk_room) {
                    data['desk_room'] = desk_room;
                }
                A.init(data);
                console.log('carData', carData);
            });
        });


        //提交定单
        function doOrder() {
            //获取要提交的数据，下新单
            var data = getData();
            console.log("data", data);
            if (type === 'book' || type === 'takeout') {
                //判断
                if (!data['name']) {
                    return $.toast('姓名不能为空！', 'text')
                }
                // 验证手机号
                var info = InputStrategy.check('isMobile', data['phone']);
                if (info) {
                    return $.toast(info, 'text');
                }
                } else {
                    data['room_desk_id'] = getRequest().room_desk_id;
                }

                $.post(api[type], {cart: data}, function (res) {
                    if (typeof res === 'string') {
                        res = JSON.parse(res);
                    }
                    // 提示信息
                    if (res.code == 200) {
                        // 下单成功，清空购物车
                        removeShopsCarData(shopsId);
                        // 如果是预定，清除缓存的 预定时间，和房桌
                        if (type === 'book') {
                            Storage.remove('arriveTime');
                            Storage.remove('deskRoom');
                        }
                        // 拿到订单ID，去支付
                        location.href = '/mobile/payment?id=' + res.data.order_id;
                    }else{
                        alert(res.info)
                    }
                });
        }

        // 菜的列表 数据适配
        function dataAdapter(data) {
            var arr = [];
            for (var i = 0, len = data.length; i < len; i++) {
                var obj = {};
                obj['dishes_id'] = data[i].id;
                obj['dishes_name'] = data[i].dishes_name;
                obj['goods_number'] = data[i].num;
                obj['price'] = data[i].price;
                obj['sell_price'] = data[i].discount_price || 0;
                obj['is_attr'] = data[i].is_attr;
                obj['spec'] = data[i].spec || '';
                arr.push(obj);
            }
            return arr;
        }

        //接口数据适配
        function getData () {
            carData = getShopsCarData(shopsId)
            var data = {};
            data['shop_id'] = shopsId;                               // 店铺ID
            data['top_price'] = $(".total").text().replace('￥',''); // 总价
            data['dish'] = dataAdapter(carData);                     // 菜的列表数据
            data['note'] = $("textarea[name='content']").val();      // 备注
            data['_token'] = _token;  // _token
           // 外卖需要的数据
           if (type === 'takeout') {
               data['name'] = $("input[name='name']").val();            // 姓名
               data['phone'] = $("input[name='phone']").val();          // 手机
               data['address_id'] = $("input[name='addressId']").val(); // 地址ID
           }else if (type === 'book') {
               desk_room  = Storage.get('deskRoom')
               arriveTime = Storage.get('arriveTime').value
               // 预定专属数据
               if (desk_room.status) {
                   desk_room = JSON.parse(desk_room.value);
               }
               //只要房桌的id
               var str = '';
               for (var i = 0, len = desk_room.length; i < len; i++) {
                   if (i < len - 1) {
                       str += desk_room[i].id + "|";
                   } else {
                       str += desk_room[i].id;
                   }
               }
               data['desk_room'] = str;
               data['arrive_time'] = arriveTime;
               data['name'] = $("input[name='name']").val();    // 姓名
               data['phone'] = $("input[name='phone']").val();  // 手机
           } else if (type === 'sweep') {
               data['room_desk_id'] = $("input[name='room_desk_id']").val();
           }else{
               alert("下单类型不存在")
           }
           return data;
        }
    </script>
@endsection


@extends('layouts/footer')
